const path = require('path')
const resolve = (dir) => path.join(__dirname, './', dir)
const {DefinePlugin} = require('webpack')
const AddAssetHtmlWebpackPlugin = require('add-asset-html-webpack-plugin')
const DllReferencePlugin = require("webpack/lib/DllReferencePlugin.js");
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin')

const config = {
    title: 'PLAIN UI DOC',                                      // 单页面应用title
    APP_NAME: 'PLAIN_UI_DOC_APPLICATION',                       // 每个应用的唯一标识，没有格式限制，只能用下划线命名，因为最后会输出为一个变量名
    publicPath: '/plain-ui-doc/',                               // 部署路径
}

const createAssetWebpackPlugin = (assets) => {
    return new AddAssetHtmlWebpackPlugin((assets || []).filter(Boolean).map(item => ({
        filepath: resolve(item),
        typeOfAsset: item.indexOf('.css') > -1 ? 'css' : 'js'
    })))
}

module.exports = {
    publicPath: config.publicPath,                       // plain-ui仓库专用
    runtimeCompiler: true,
    devServer: {
        port: '3334',
        // 关闭主机检查，使微应用可以被 fetch
        disableHostCheck: true,
        // 子应用需要配置跨域
        headers: {
            "Access-Control-Allow-Origin": "*",
        }
    },
    outputDir: resolve('docs'),
    configureWebpack: {
        module: {
            rules: [
                {
                    test: /\.md$/,
                    use: ['text-loader'],
                },
            ],
        },
        resolve: {
            extensions: ['.ts', '.tsx', 'js', 'jsx', 'json'],
        },
        output: {
            library: `CustomApplication${config.APP_NAME}`,             // 微应用的包名，这里与主应用中注册的微应用名称一致
            libraryTarget: "umd",                                       // 将你的 library 暴露为所有的模块定义下都可运行的方式
            jsonpFunction: `webpackJsonp_${config.APP_NAME}_project`,   // 按需加载相关，设置为 webpackJsonp_#{APP_NAME}_project 即可
        },
        plugins: [
            new DefinePlugin({
                ENV: JSON.stringify(config),
                // APP_ENV: JSON.stringify(require(resolve(`story/env/config/${process.env.APP_ENV}.js`)))
            }),
            new DllReferencePlugin({manifest: require("./dll/dll-vendor.manifest.json"),}),
            createAssetWebpackPlugin([
                'src/lib/markdown/markdown-it-attrs.js',
                'src/lib/babel.min.js',
                'build/jsx-next.plugin.js',
                'src/lib/parse-xml.min.js',
                'src/lib/prism/prism.js', 'src/lib/prism/prism.css',
                'src/lib/iconfont_js/iconfont.js', 'src/lib/iconfont_css/iconfont.css',
                'dll/dll-vendor.min.js',
            ]),
        ]
    },
    pages: {
        index: {
            entry: resolve('src/pages/index/main'),
            template: 'public/index.html',
            filename: 'index.html',
            title: config.title,
            chunks: ['chunk-vendors', 'chunk-common', 'index'],
        },
        run: {
            entry: resolve('src/pages/run/main'),
            template: 'public/index.html',
            filename: 'run.html',
            title: 'PLAIN DESIGN DEBUGGER',
            chunks: ['chunk-vendors', 'chunk-common', 'run'],
        },
    },
    chainWebpack(config) {
        config.plugin('monaco').use(new MonacoWebpackPlugin())

        config.resolve.alias
            .set('@', resolve('src'))
            .set('src', resolve('src'))
            .set('~', resolve('node_modules'))
            .set('plain-ui-composition/src/index', resolve('abc'))

        if (process.env.NODE_ENV === 'development') {
            config.resolve.alias.set('react-dom', 'react-dom/cjs/react-dom.production.min')
        }
        config.plugins
            .delete('prefetch-index')
            .delete('preload-index')

        /*移除ts-loader，由babel-loader，通过 preset-react, preset-env, preset-typescript来编译tsx文件。否则有ts-loader先编译文件，会导致JSXModel plugin无效*/
        // config.module.rule('tsx').uses.delete('ts-loader')
        config.module.rule('tsx').use('ts-loader').loader('ts-loader').tap(options => {
            if (!options.compilerOptions) {options.compilerOptions = {}}
            options.compilerOptions.jsx = 'preserve'
            return options
        })
    },
    css: {
        loaderOptions: {
            sass: {
                additionalData: `@import "~plain-ui/src/styles/global-import.scss";`
            }
        }
    },
}
